/**
 *
 */
package com.adream.scalpel.security.server.system;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.adream.scalpel.common.server.domain.User;

/**
 * @author apuranik
 * 
 */
public class ScalpelUserDetailsService implements UserDetailsService {
    private PersistenceManagerFactory pmf;

    @SuppressWarnings("unchecked")
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        PersistenceManager pm = pmf.getPersistenceManager();
        Query query = pm.newQuery(User.class, "userName == paramUserName");
        query.declareParameters("String paramUserName");

        ScalpelUserDetails userDetails = null;

        try {
            List<User> users = (List<User>) query.execute(username);
            if (users.size() == 0) {
                throw new UsernameNotFoundException("User: " + username + " does not exist");
            } else {
                User user = users.get(0);
                userDetails = new ScalpelUserDetails(user.getUserName(), user.getPassword(), user.isEnabled());
            }
        } finally {
            query.closeAll();
            if (pm != null) {
                pm.close();
            }
        }
        return userDetails;
    }

    @SuppressWarnings("unchecked")
    public void setPmf(PersistenceManagerFactory pmf) {
        this.pmf = pmf;

        // Let's create the admin user if its not present in the database.
        PersistenceManager pm = pmf.getPersistenceManager();
        Query query = pm.newQuery(User.class, "userName == 'admin'");

        try {
            List<User> users = (List<User>) query.execute();
            if (users.size() == 0) {
                User adminUser = new User("admin");
                adminUser.setPassword("password");
                adminUser.setDisplayName("The Administrator");
                adminUser.setEnabled(true);
                pm.makePersistent(adminUser);
            }

        } finally {
            query.closeAll();
            if (pm != null) {
                pm.close();
            }
        }
    }
}
